package top.anonyeast.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

@Component
public class IpUtils {
    @Resource(name = "httpUtils")
    private HttpUtils httpUtils;

    /**
     * 获取用户外网IP地址
     * <p>
     * 不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     *
     * @return ip
     */
    public String getOuterIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inetAddr = null;
                try {
                    inetAddr = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                assert inetAddr != null;
                ipAddress = inetAddr.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        System.out.println("客户端IP地址: " + ipAddress);
        return ipAddress;
    }

    /**
     * 调用腾讯位置服务接口查询地理位置
     *
     * @param ip
     * @return
     */
    public String getLocationByIP(String ip) {
        try {
            String api = "https://apis.map.qq.com/ws/location/v1/ip?key=VATBZ-XFGWK-GAKJU-AUXRO-GND25-IHBQF";
            String response_text = httpUtils.get(api + "&ip=" + ip);
            //解析返回的json字符串
            ObjectMapper jackson = new ObjectMapper();
            Map<String, Object> response_json = jackson.readValue(response_text, Map.class);
            //判断是否获取成功
            if ("Success".equals(response_json.get("message"))) {
                Map<String, Object> result = (Map<String, Object>) response_json.get("result");
                Map<String, Object> ad_info = (Map<String, Object>) result.get("ad_info");
                String nation = (String) ad_info.get("nation");//国家
                String province = (String) ad_info.get("province");//省
                String city = (String) ad_info.get("city");//市
                if (province.length() > 0 || city.length() > 0){
                    return province + city;
                }else{
                    return nation;
                }
            } else {
                return (String) response_json.get("message");
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

}